/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bm.garage;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.ejb.Stateless;

/**
 *
 * @author BV
 */
@WebService(serviceName = "GarageWS")
@Stateless()
public class TeamV_GarageWS {
    

    /** This web service will book the first available service bay according to date and size including a mechanic */
    @WebMethod(operationName = "BookServiceBay")
    @SuppressWarnings("CallToThreadDumpStack")
    public ServiceBayBookingResponse bookBayAndMechanic( @WebParam(name = "bookingRequest") ServiceBayBookingRequest booking ) {
        
        Calendar startCalDate = Calendar.getInstance();
        Calendar endCalDate   = Calendar.getInstance();
        Integer numberOfDays  = booking.getDays();
        String size           = booking.getSize().toString();
        Connection con        = null;
        Statement stmt        = null;
        ResultSet rset        = null;
        
        ServiceBayBookingResponse res = new ServiceBayBookingResponse();
        
        try {
            
            //Connect to db
            Class.forName("com.mysql.jdbc.Driver");
            //java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://linuxws.scitech.qut.edu.au:3306/n4193989", "n4193989", "bjorn123");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/n4193989", "n4193989", "bjorn123");
            stmt = con.createStatement();
            
            String firstAvailableDateSQL = "SELECT MAX(enddate) FROM servicebay WHERE size=\"" + size + "\";";
            
            rset = stmt.executeQuery(firstAvailableDateSQL);
            
            java.sql.Date startDate = null;
            if(rset.next()) {
                startDate = rset.getDate( 1 );
            }
            
            startCalDate = Calendar.getInstance();
            startCalDate.setTime( startDate );
            startCalDate.add( Calendar.DATE, 1); // Operate in whole days, thus start work the next day
       
            while( startCalDate.get( Calendar.DAY_OF_WEEK ) == Calendar.SATURDAY || startCalDate.get( Calendar.DAY_OF_WEEK ) == Calendar.SUNDAY )
                startCalDate.add( Calendar.DATE, 1);
            
            System.out.println( "firstdate:" + startCalDate.get(Calendar.YEAR) + "-" + (startCalDate.get(Calendar.MONTH) + 1) + "-" + startCalDate.get(Calendar.DATE));
            
            endCalDate.setTime( startDate );
            
            int numOfDays = numberOfDays.intValue();
            int count = 0;
            
            while( count < numOfDays ) {
                
                endCalDate.add( Calendar.DATE, 1 );
                
                //if a weekend add extra days
                if( endCalDate.get( Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || 
                    endCalDate.get( Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ) {
                    numOfDays = numOfDays+1;
                }
                      
                count++;
            }
            
            numberOfDays = new Integer(numOfDays);
            
            System.out.println( "enddate:" + endCalDate.get(Calendar.YEAR) + "-" + (endCalDate.get(Calendar.MONTH) + 1) + "-" + endCalDate.get(Calendar.DATE));
            
            java.sql.Date endDate = new java.sql.Date(endCalDate.getTime().getTime());
            
            String insertSQL = "INSERT INTO servicebay (size, startdate, enddate) VALUES('"+ size + "','" + startDate.toString() + "','" + endDate.toString() +"');";
            stmt.executeUpdate( insertSQL );
            
            rset.close();
            stmt.close();
            con.close();
            
        } catch (SQLException ex) {
            res.setStartDate("SQLException:" + ex.getMessage());
            //ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            res.setStartDate("ClassNotFoundException:" + ex.getMessage());
            //ex.printStackTrace();
        } catch (Exception e) {
            res.setStartDate("Exception:" + e.getMessage());
            //e.printStackTrace();
        } finally {
            
            try {
                rset.close();
                stmt.close();
                con.close();
            } catch (Throwable t ) {
                //do nothing..
            }
            
        }
        
        //ServiceBayBookingResponse res = new ServiceBayBookingResponse();
        int syear = startCalDate.get(Calendar.YEAR);
        int smonth = startCalDate.get(Calendar.MONTH)+1;
        int sday = startCalDate.get(Calendar.DAY_OF_MONTH);
        
        int eyear = endCalDate.get(Calendar.YEAR);
        int emonth = endCalDate.get(Calendar.MONTH)+1;
        int eday = endCalDate.get(Calendar.DAY_OF_MONTH);
        
        res.setStartDate(syear+"-"+smonth+"-"+sday);
        res.setEndDate(eyear+"-"+emonth+"-"+eday);
        

        res.setDays( numberOfDays );
        res.setSize( size );
       
        return res;
    }
    
    public static void main( String[] args ) {
        
        TeamV_GarageWS ws = new TeamV_GarageWS();
        
        ServiceBayBookingRequest req = new ServiceBayBookingRequest();
        req.setDays( new Integer(2));
        req.setSize( ServiceBayBookingRequest.BaySize.S) ;
        
        ServiceBayBookingResponse res = ws.bookBayAndMechanic(req);
        
        System.out.print( "Days: " + res.getDays() );
        System.out.print( ", StartDate: " + res.getStartDate().toString() );
        System.out.print( ", EndDate: " + res.getEndDate().toString() );
        System.out.println( ", Size: " + res.getSize() );  
        
        
        
        
    }
    
}
